import React, { useEffect, useState } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { Table, Pagination, Spin, message, InputNumber, Button, Select } from 'antd';
import axios from 'axios';
import './TradeManual.scss';

const TradeManualAsset = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();

  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [adjustments, setAdjustments] = useState(
    JSON.parse(localStorage.getItem('adjustments') || '{}')
  );
  const [assetType, setAssetType] = useState(searchParams.get('type') || 'stock');
  const token = localStorage.getItem('jwt_token');

  useEffect(() => {
    if (!token) {
      message.error("用户未登录");
      navigate("/login");
    }
  }, [token, navigate]);

  useEffect(() => {
    if (!searchParams.get('page')) {
      setSearchParams({ page: '1', type: assetType });
    }
  }, [searchParams, setSearchParams, assetType]);

  const page = parseInt(searchParams.get('page') || '1', 10);

  useEffect(() => {
    if (!token) return;

    const fetchAssetData = async () => {
      setLoading(true);
      try {
        // 根据 assetType 获取不同类型的资产数据
        if (assetType !== 'stock' && assetType !== 'fund') {
          message.error('不支持的资产类型');
          return;
        }

        // 创建一个动态的查找url，根据类型分类讨论
        // 创建一个查找字符串

        let search_type= assetType;
        if(assetType === 'stock') {
          search_type = 'stocklist';
        } else if (assetType === 'fund') {
          search_type = 'fund';
        }

        const res = await axios.get(`/api/ui/${search_type}?page=${page}`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        if (res.data.code === 0) {
          const transformData = res.data.data.map((item) => ({
            ...item,
            最新价: item.最新价 / 100,
            涨跌幅: (item.涨跌幅 / 100).toFixed(2) + '%',
          }));
          setData(transformData);
        } else {
          message.error('获取数据失败: ' + res.data.message);
        }
      } catch (error) {
        message.error('请求出错');
      } finally {
        setLoading(false);
      }
    };

    fetchAssetData();
  }, [page, assetType, token]);

  const handleAdjustChange = (code, value) => {
    if (value == null) return;
    const updatedAdjustments = { ...adjustments, [code]: value };
    setAdjustments(updatedAdjustments);
    localStorage.setItem('adjustments', JSON.stringify(updatedAdjustments));
  };

  const handleSubmitAdjustments = async () => {
    const adjustmentsArray = Object.keys(adjustments).map((code) => {
      const record = data.find((item) =>
        assetType === 'stock' ? item.股票代码 === code : item.基金代码 === code
      );
      if (!record) return null;

      const CN_assetType = assetType === 'stock' ? '股票' : '基金';


    
      const return_json={
        code: record.股票代码 || record.基金代码,
        name: record.股票名称 || record.基金名称,
        type: CN_assetType,
        quantity: adjustments[code] || 0,
        cost_price: record.最新价 || 0,
      }
            // 打印一下我返回的结果在控制台
      console.log('提交的调整数据:', return_json);

      return return_json;
    }).filter((item) => item !== null);

    try {
      console.log('提交的调整数据:', adjustmentsArray);
      const res = await axios.post('/api/product/add', adjustmentsArray, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      if (res.data.code === 0) {
        message.success('持仓调整提交成功');
        setAdjustments({});
        localStorage.removeItem('adjustments');
      } else {
        message.error('提交失败: ' + res.data.message);
      }
    } catch (error) {
      message.error('请求出错');
    }
  };

  const stockColumns = [
    { title: '股票代码', dataIndex: '股票代码', key: 'code' },
    { title: '股票名称', dataIndex: '股票名称', key: 'name' },
    { title: '最新价', dataIndex: '最新价', key: 'price', render: (val) => val.toFixed(2) },
    { title: '涨跌幅', dataIndex: '涨跌幅', key: 'percent' },
    {
      title: '调整持仓',
      key: 'adjust',
      render: (_, record) => (
        <InputNumber
          min={-1000}
          max={1000}
          value={adjustments[record['股票代码']]}
          onChange={(value) => handleAdjustChange(record['股票代码'], value)}
          placeholder="调整数量"
        />
      ),
    },
  ];

  const fundColumns = [
    { title: '基金代码', dataIndex: '基金代码', key: 'code' },
    { title: '基金名称', dataIndex: '基金名称', key: 'name' },
    { title: '最新价', dataIndex: '最新价', key: 'price', render: (val) => val.toFixed(2) },
    { title: '涨跌幅', dataIndex: '涨跌幅', key: 'percent' },
    {
      title: '调整持仓',
      key: 'adjust',
      render: (_, record) => (
        <InputNumber
          min={-1000}
          max={1000}
          value={adjustments[record['基金代码']]}
          onChange={(value) => handleAdjustChange(record['基金代码'], value)}
          placeholder="调整数量"
        />
      ),
    },
  ];

  const selectedColumns = assetType === 'stock' ? stockColumns : fundColumns;

  return (
    <div className="multi-asset-page">
      <h2>多资产行情 - 调整持仓</h2>
      <Select
        value={assetType}
        onChange={(value) => {
          setAssetType(value);
          
          let search_type = value;
          if(value === 'stock') {
            search_type = 'stocklist';
          }
          else if(value === 'fund') {
            search_type = 'fund';
          }

          setSearchParams({ page: '1', type: search_type });
        }}
        style={{ marginBottom: '16px' }}
      >
        <Select.Option value="stock">股票</Select.Option>
        <Select.Option value="fund">基金</Select.Option>
      </Select>
      <Spin spinning={loading}>
        <Table
          dataSource={data}
          columns={selectedColumns}
          rowKey={(record) => record.股票代码 || record.基金代码}
          pagination={false}
        />
        <Pagination
          current={page}
          pageSize={20}
          total={286 * 20}
          onChange={(newPage) => {
            if(assetType === 'stock') {
              setSearchParams({ page: newPage.toString(), type: 'stocklist' });
            }
            else if(assetType === 'fund') {
              setSearchParams({ page: newPage.toString(), type: 'fund' });
            }
          }}
          showSizeChanger={false}
        />
        <Button
          type="primary"
          style={{ marginTop: '16px' }}
          onClick={handleSubmitAdjustments}
          disabled={Object.keys(adjustments).length === 0}
        >
          提交持仓调整
        </Button>
      </Spin>
    </div>
  );
};

export default TradeManualAsset;
